package com.mlming.springboot.vo;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.mlming.springboot.enums.ResponseEnum;
import lombok.Data;
import org.springframework.validation.BindingResult;

import java.io.Serializable;

// 响应信息实体类对象
@Data
@JsonInclude(value = JsonInclude.Include.NON_NULL) // 在以json形式响应该对象时,会把里面的null值去除
// 由于看接口文档里面, 那个data属性是一个类型不定的对象,所以要用到泛型
public class ResponseVo<T> implements Serializable {

    private static final long serialVersionUID = -5149283776018510278L;

    private Integer status;
    private String msg;
    private T data;

    public ResponseVo() {
    }

    public ResponseVo(Integer status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    // 返回具有全部信息的响应对象
    public static <T> ResponseVo<T> success(T data) {
        ResponseVo<T> responseVo = new ResponseVo<T>();
        responseVo.setData(data);
        responseVo.setStatus(ResponseEnum.SUCCESS.getCode());
        return responseVo;
    }
    // 返回只具有code,msg的成功的响应对象
    public static ResponseVo success() {
        return new ResponseVo(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getDesc());
    }
    // 传递枚举返回错误响应对象
    public static ResponseVo error(ResponseEnum responseEnum) {
        return new ResponseVo(responseEnum.getCode(), responseEnum.getDesc());
    }
    // 根据发过来的BindingResult来获取属性错误信息来返回错误响应对象
    public static ResponseVo error(ResponseEnum responseEnum, BindingResult bindingResult) {
        return new ResponseVo(responseEnum.getCode(), bindingResult.getFieldError().getField() + " " + bindingResult.getFieldError().getDefaultMessage());
    }
    // 根据发来的错误枚举 以及 msg进行返回
    public static ResponseVo error(ResponseEnum responseEnum, String msg) {
        return new ResponseVo(responseEnum.getCode(), msg);
    }
}
